﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using TIBCO.Rendezvous;

namespace Tibco.ServiceModel
{
    internal sealed class TibcoChannelListener<TChannel> : TibcoChannelListenerBase<IInputChannel>
    where TChannel : class, IChannel
    {
        private IInputChannel m_channel;
        private NetTransport m_transport;
        private CMQueueTransport m_cmTransport;
        private TibcoTransportBindingElement bindingElement;

        //private IModel m_model;

        internal TibcoChannelListener(TibcoTransportBindingElement bindingElement, BindingContext context) : base(context)
        {
            this.m_channel = null;
            this.m_transport = null;
            this.m_cmTransport = null;

            this.bindingElement = bindingElement;
        }

        protected override IInputChannel OnAcceptChannel(TimeSpan timeout)
        {
            if (this.m_channel != null)
            {
                return null;
            }
            this.m_channel = new TibcoInputChannel(base.Context, this.m_cmTransport, new EndpointAddress(this.Uri.ToString()));
            this.m_channel.Closed += (s, e)=> { base.Close(); };
            return this.m_channel;
        }

        protected override void OnClose(TimeSpan timeout)
        {
            if (this.m_channel != null)
            {
                this.m_channel.Close();
                this.m_channel = null;
            }
            if (this.m_cmTransport != null)
            {
                //this.m_bindingElement.Close(this.m_model, timeout);
                this.m_cmTransport.Destroy();
                this.m_cmTransport = null;
            }
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            ///this.cmTransport = this.m_bindingElement.Open(timeout);
            TIBCO.Rendezvous.Environment.Open();
            this.m_transport = new NetTransport(bindingElement.Service, bindingElement.Network, bindingElement.Deamon);
            this.m_cmTransport = new CMQueueTransport(this.m_transport, bindingElement.DQName);
        }

        protected override bool OnWaitForChannel(TimeSpan timeout)
        {
            return false;
        }
    }
}